package com.springboot.controller;

import com.alibaba.fastjson.JSONObject;
import com.springboot.util.RSAUtils;
import com.springboot.util.RsaConstans;
import com.springboot.util.SignUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author: TongRui乀
 * @Date: 2019/6/26 14:57
 * @description：
 */
@RestController
@RequestMapping("api")
public class WebAPIController {


    @RequestMapping("test")
    @ResponseBody
    public JSONObject demo(@RequestParam(value = "realName")String realName,
                           @RequestParam(value = "phone")String phone,
                           @RequestParam(value = "idCard")String idCard,
                           @RequestParam(value = "bankCard")String bankCard,
                           @RequestParam(value = "sign")String sign){

        JSONObject responseObject = new JSONObject();
        Map<String,Object> map = new ConcurrentHashMap<String,Object>();

        //签名参数验证
        //封装参数进行验证
        map.put("realName",realName);
        map.put("phone",phone);
        map.put("idCard",idCard);
        map.put("bankCard",bankCard);

        System.err.println(SignUtils.generateSortSign(map));

        //注意看,这里使用的就是客户端的公钥进行签名的解密
        boolean isTrue = RSAUtils.signVerify(sign,SignUtils.generateSortSign(map), RsaConstans.client.PUBLIC);

        if (!isTrue){
            responseObject.put("code", "1000");
            responseObject.put("message", "签名错误");
        }

        //0000是失败,1111是成功
        String code = responseObject.getString("code");
        if(code!=null && code.equals("1000")){

            System.err.println("鉴权失败");

            map.clear();
            map.put("result","0000");
            map.put("resultDesc",responseObject.getString("message"));

            //使用服务端私钥生成返回的签名
            String ret_sign = RSAUtils.sign(SignUtils.generateSortSign(map),RsaConstans.Server.pri);
            map.put("ret_sign",ret_sign);
            responseObject.put("Object", map);

        }else {

            System.err.println("鉴权成功");

            map.clear();
            map.put("result","ok");
            map.put("resultDesc","验证通过");

            //使用服务端私钥生成返回的签名
            String ret_sign = RSAUtils.sign(SignUtils.generateSortSign(map),RsaConstans.Server.pri);
            map.put("ret_sign",ret_sign);
            responseObject.put("Object", map);
            responseObject.put("message", "验证成功");
        }

        return responseObject;
    }


}
